package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShopingCardMapper;
import com.sky.service.ShopingCardService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.print.DocFlavor;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShopingCardServicelmpl implements ShopingCardService {
    @Autowired
    private ShopingCardMapper shopingCardMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;


    @Override
    public void addShopingCard(ShoppingCartDTO shoppingCartDTO) {
        //查询shoping_card表中是否已经有该菜品或套餐
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts = shopingCardMapper.select(shoppingCart);

        //若该表中已经存在则只需number+1
        if (shoppingCarts != null && shoppingCarts.size() != 0) {
            ShoppingCart shoppingCart1 = shoppingCarts.get(0);
            shoppingCart1.setNumber(shoppingCart1.getNumber() + 1);
            shopingCardMapper.updata(shoppingCart1);

            return  ;
        }

        //若不存在则需要插入该表中
        Long dishId = shoppingCartDTO.getDishId();
        if (dishId != null) {
            //添加菜品到购物车  不能用BeanUtils.copyProperties();因为菜品表的id会和shopingcard表中的id混淆
            //添加到购物车的是菜品

            Dish dish = dishMapper.getById(dishId);
            shoppingCart.setName(dish.getName());
            shoppingCart.setImage(dish.getImage());
            shoppingCart.setAmount(dish.getPrice());
        } else {
           //添加到购物车的是套餐
            Setmeal setmeal = setmealMapper.getById(shoppingCartDTO.getSetmealId());
            shoppingCart.setName(setmeal.getName());
            shoppingCart.setImage(setmeal.getImage());
            shoppingCart.setAmount(setmeal.getPrice());
        }
        shoppingCart.setNumber(1);
        shoppingCart.setCreateTime(LocalDateTime.now());
        shopingCardMapper.insert(shoppingCart);
    }

    /**
     * 查看购物车
     * @return
     */
    public List<ShoppingCart> showShoppingCart() {
        return shopingCardMapper.select(ShoppingCart.
                builder().
                userId(BaseContext.getCurrentId()).
                build());
    }

    /**
     * 清空购物车商品
     */
    public void cleanShoppingCart() {
        shopingCardMapper.deleteByUserId(BaseContext.getCurrentId());
    }
}
